//@ts-nocheck
import { ExportData, AdditionData } from './interface'

//  eslint-disable-next-line
CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) {
  if (typeof text !== 'string' || typeof x !== 'number' || typeof y !== 'number') {
    return
  }

  // eslint-disable-next-line @typescript-eslint/no-this-alias
  let context = this
  let canvas = context.canvas

  if (typeof maxWidth === 'undefined') {
    maxWidth = canvas?.width || 300
  }
  if (typeof lineHeight === 'undefined') {
    lineHeight =
      (canvas && parseInt(window.getComputedStyle(canvas).lineHeight)) ||
      parseInt(window.getComputedStyle(document.body).lineHeight)
  }

  // 字符分隔为数组
  let arrText = text.split('')
  let line = ''

  // 如果需要换行, 调整垂直居中坐标(此处只针对两行做了简单处理, 多行之后根据需求维护)
  let initMetrics = context.measureText(text)
  let initWidth = initMetrics.width
  if (initWidth > maxWidth) y -= lineHeight / 2

  for (let n = 0; n < arrText.length; n++) {
    let testLine = line + arrText[n]
    let metrics = context.measureText(testLine)
    let testWidth = metrics.width
    if (testWidth > maxWidth && n > 0) {
      context.fillText(line, x, y)
      line = arrText[n]
      y += lineHeight
    } else {
      line = testLine
    }
  }
  context.fillText(line, x, y)
  return y
}

/** 该方法用来绘制圆角矩形
 *@param cxt:canvas的上下文环境
 *@param x:左上角x轴坐标
 *@param y:左上角y轴坐标
 *@param width:矩形的宽度
 *@param height:矩形的高度
 *@param lineWidth:线条粗细
 *@param strokeColor:线条颜色
 **/
// eslint-disable-next-line max-params
function strokeRect(
  ctx,
  x,
  y,
  width,
  height,
  /* optional */ lineWidth?,
  /* optional */ strokeColor?
) {
  ctx.save()
  ctx.lineWidth = lineWidth || 2 // 若是给定了值就用给定的值否则给予默认值2
  ctx.strokeStyle = strokeColor || '#3f60fc'
  ctx.strokeRect(x, y, width, height)
  ctx.restore()
}

// eslint-disable-next-line max-params
function drawDot(ctx, x, y, index) {
  ctx.beginPath()
  ctx.fillStyle = 'white'
  ctx.arc(x, y, 12, 0, 2 * Math.PI)
  ctx.fill()
  ctx.closePath()
  ctx.font = '14px Arial'
  ctx.fillStyle = 'black'
  ctx.fillText(index, x - 4, y + 4)
}

function drawBackground(context: CanvasRenderingContext2D, width: number, height: number) {
  context.fillStyle = 'white'
  context.fillRect(0, 0, width, height)
}

function saveImage(imgSrc: string) {
  const saveLink = document.createElement('a')
  saveLink.href = imgSrc
  saveLink.download = 'statistics_image.png'
  saveLink.click()
}

export const exportHeatMapImage = async (
  imgSrc: string,
  data: ExportData,
  additionData?: any,
  like = '1'
  // eslint-disable-next-line max-params
) => {
  const exportCanvas = document.createElement('canvas')
  const context: CanvasRenderingContext2D = exportCanvas.getContext('2d')
  const canvasWidth = data.width
  const canvasHeight = data.height
  exportCanvas.width = canvasWidth
  exportCanvas.height = canvasHeight

  /** 绘制图片 */
  const chartImg = await getImageInfo(imgSrc)

  const imgWidth = chartImg.width
  const imgHeight = chartImg.height

  const drawImgWidth = canvasWidth
  const drawImgHeight = (drawImgWidth * imgHeight) / imgWidth

  // /** 绘制题型文字 */
  // drawTypeName(context, data.typeName)

  // !data.hideSubmitCount && drawSubmitCount(context, stemYCoo + 33 + 12, `提交人数：${data.submitCount}人`)

  // drawStem(context, data.stem)
  /** 绘制背景 */
  drawBackground(context, canvasWidth, 1334)

  context.drawImage(chartImg, 0, 0, canvasWidth, canvasHeight)
  /** 附加的信息 */
  if (additionData) {
    if (additionData?.length > 0) {
      // eslint-disable-next-line array-callback-return
      additionData.map((item, index) => {
        if (item.width > 0 && item.height > 0) {
          context.fillStyle = like === '1' ? 'rgba(143, 37, 36, 0.2)' : 'rgba(7, 19, 43, 0.2)'
          context.fillRect(
            parseFloat(item.xOffset),
            parseFloat(item.yOffset),
            parseFloat(item.width),
            parseFloat(item.height)
          )
          context.restore()
          strokeRect(
            context,
            parseFloat(item.xOffset),
            parseFloat(item.yOffset),
            parseFloat(item.width),
            parseFloat(item.height),
            2,
            like === '1' ? '#ff4b49' : '#3f60fc'
          )
          drawDot(context, parseFloat(item.xOffset), parseFloat(item.yOffset), index + 1)
        }
      })
    }
  }
  const dataURL = exportCanvas.toDataURL('image/png')
  saveImage(dataURL)
}

const getImageInfo = (imgSrc: string): Promise<HTMLImageElement> => {
  const chartImg: HTMLImageElement = new Image()
  // 在 URL 后面加一个时间戳就不会报错了，也不需要服务端设置
  // 当然了，这样的话 cdn 也会失效，没有缓存作用
  let timestamp = new Date().getTime()
  chartImg.setAttribute('crossOrigin', 'anonymous')
  chartImg.src = imgSrc + '?' + timestamp

  return new Promise((reslove, reject) => {
    chartImg.onload = () => {
      reslove(chartImg)
    }
  })
}
